<script setup>
import { ref } from 'vue';
import { getPolicy, deletePicture } from '@/apis/policy.js'
import { nanoid } from 'nanoid'
import { Plus } from '@element-plus/icons-vue'

const props = defineProps({
    imageList:{
        type:Array,
        default:[],
    },
    uploadType:{
        type:String,
    },
    limitCount:{
        type:Number,
        default:30,
    },
    width:{
        type:Number,
        default:180,
    },
    height:{
        type:Number,
        default:180,
    },
})


// 凭证变量
const policyObj = ref({});
const gatUploadParams = async(file)=>{
    const res =  await getPolicy();
    policyObj.value = res.data;
    policyObj.value.key = policyObj.value.dir + props.uploadType + "/" + nanoid() + file.name;
    return policyObj.value;
}

const emits = defineEmits(['upload:imageList'])

// 文件上传成功
const handlePictureSuccess =(res,file) =>{
    ElMessage({
        message: '上传成功',
        type: 'success',
    })

    props.imageList.push({
        name:file.name,
        deleteMark:policyObj.value.key, // 删除标记，用来删除删除到服务器的文件
        url:policyObj.value.host + '/' + policyObj.value.key,
    })
    emits('update:imageList',props.imageList);
}

// 删除文件
const handleRemove = async(uploadFile,uploadFiles) => {
    // url会转换成blob,没办法直接使用file.url进行删除
    let deleteMark = props.imageList.find(item => item.name === uploadFile.name).deleteMark
    await deletePicture(deleteMark)
    .then(res=>{
        if(res.code === 0){
            ElMessage({
                message: '删除成功',
                type: 'success',
            })
            props.imageList = props.imageList.filter(item => item.name !== uploadFile.name);
            emits('update:picture',props.imageList);
        }
    })
}

const handleExceed=(files, fileList)=>{
    ElMessage({
        message: '最多只能上传' + props.limitCount + "张图片",
        type: 'warning',
    })
}

const dialogImageUrl = ref('')
const dialogVisible = ref(false)

const handlePictureCardPreview= (uploadFile) => {
  dialogImageUrl.value = uploadFile.url;
  dialogVisible.value = true
}

</script>

<template>
        <el-upload
            action="http://pet-supplies-oss.oss-cn-beijing.aliyuncs.com"
            v-model:file-list="props.imageList"
            :data="gatUploadParams"
            list-type="picture-card"
            :limit="props.limitCount"
            :on-success="handlePictureSuccess"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-exceed="handleExceed"
        >
            <el-icon><Plus /></el-icon>
        </el-upload>

        <el-dialog v-model="dialogVisible">
            <img w-full :src="dialogImageUrl" style="width: 100%;" alt="Preview Image" />
        </el-dialog>
</template>

<style scoped lang='scss'>

</style>